// 1.导入 React
import React from "react"
import "./comment.css"

// 2.创建React组件
class Comment extends React.Component{
    state={
        // 评论数组
        commentList:[
            {name:"张三",content:"哈哈哈"},
            {name:"李四",content:"呵呵呵"},
            {name:"王五",content:"哈哈哈"},
        ],
        // 评论人
        userName:"",
        // 评论内容
        userContent:""
    }
    renderList(){
        if(this.state.commentList.length ===0 ){
            return <p>暂无评论，快点去评论吧</p>
        }else{
            return <ul>
            {this.state.commentList.map((item,index)=><li key={index}>
                <h2>评论人：{item.name}</h2>
                <p>评论内容：{item.content}</p>
            </li>)}
            </ul>
        }
    }
    getInput=(e)=>{
        this.setState({
            [e.target.name]:e.target.value
        })
        console.log("评论人：",this.state);

    }
    addList=()=>{
        let {commentList,userName,userContent}=this.state
        // 判断评论人和评论内容是否存在
        if(userName!=="" && userContent!==""){
            let newList=[...commentList,{
                name:userName,
                content:userContent
            }]
            this.setState({
                commentList:newList,
                userName:"",
                userContent:""
            })
        }else{
            alert("请输入相关内容！");
        }
        
    }
    render(){
        let {userName,userContent}=this.state
        return <div className="box">
            <input type="text" placeholder="请输入评论人" name="userName" value={userName} onChange={this.getInput}></input>
            <textarea placeholder="请输入评论内容" name="userContent" value={userContent} onChange={this.getInput}></textarea>
            <button onClick={this.addList}>发布评论</button>

            {/* 评论列表区域 */}
            {
               this.renderList() 
            }


            
        </div>
    }
}

// 3.导出组件
export default Comment